package cc.ok200.muzhi;

import android.content.Intent;
import android.graphics.Color;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowInsetsController;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.GravityCompat;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alivc.live.pusher.AlivcLiveBase;
import com.alivc.live.pusher.AlivcLiveBaseListener;
import com.alivc.live.pusher.AlivcLivePushConstants;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_FLOAT_WINDOW = 1001;
    private static final int REQUEST_MEDIA_PROJECTION = 1002;
    
    private DrawerLayout drawerLayout;
    private RecyclerView rvPlugins;
    private PluginAdapter pluginAdapter;
    private Switch switchFloatWindow;
    private Switch switchScreenRecording;

    private JSONArray pluginsArray = new JSONArray();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 启动长连接
        WebSocketClient.launch();
        
        // 设置沉浸式状态栏，使应用内容延伸到状态栏
        setImmersiveStatusBar();
        
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        // 从资源文件加载插件数据
        loadPluginsFromJson();
        
        // 初始化抽屉菜单
        drawerLayout = findViewById(R.id.drawer_layout);
        
        // 设置抽屉菜单的顶部边距，使其适应状态栏
        View navView = findViewById(R.id.nav_view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 获取状态栏高度
            int statusBarHeight = 0;
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
            }
            
            // 设置抽屉头部视图的顶部内边距
            View headerView = ((LinearLayout)navView).getChildAt(0);
            if (headerView != null) {
                headerView.setPadding(
                    headerView.getPaddingLeft(),
                    headerView.getPaddingTop() + statusBarHeight,
                    headerView.getPaddingRight(),
                    headerView.getPaddingBottom()
                );
            }
        }
        
        // 设置折叠按钮
        ImageButton btnMenu = findViewById(R.id.btn_menu);
        btnMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开抽屉菜单
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        
        // 设置市场按钮
        ImageButton btnMarket = findViewById(R.id.btn_market);
        btnMarket.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到市场页面
                Intent intent = new Intent(MainActivity.this, MarketActivity.class);
                startActivity(intent);
            }
        });
        
        // 初始化悬浮窗开关
        setupFloatWindowSwitch();
        
        // 初始化屏幕录制开关
        setupScreenRecordingSwitch();
        
        // 设置应用详情点击事件（原系统设置）
        LinearLayout systemSettings = findViewById(R.id.layout_system_settings);
        systemSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到当前应用的系统设置页面
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
            }
        });
        
        // 设置更多设置点击事件
        LinearLayout moreSettings = findViewById(R.id.layout_more_settings);
        moreSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到系统设置页面
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        
        // 设置退出登录点击事件
        LinearLayout logout = findViewById(R.id.layout_logout);
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 删除token文件
                Storage.write(".token", "");
                
                // 跳转到登录页面
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                finish();
            }
        });
        
        // 初始化插件列表
        setupPluginRecyclerView();
    }
    
    /**
     * 初始化悬浮窗开关
     */
    private void setupFloatWindowSwitch() {
        // 获取悬浮窗权限布局和开关
        LinearLayout layoutFloatWindow = findViewById(R.id.layout_float_window);
        switchFloatWindow = findViewById(R.id.switch_float_window);
        
        // 检查并更新悬浮窗权限状态
        boolean hasPermission = checkFloatWindowPermission();
        switchFloatWindow.setChecked(hasPermission);
        
        // 设置开关点击事件
        switchFloatWindow.setOnClickListener(v -> {
            if (switchFloatWindow.isChecked()) {
                // 请求悬浮窗权限
                requestFloatWindowPermission();
            } else {
                // 关闭悬浮窗功能
                Toast.makeText(MainActivity.this, "已关闭悬浮窗功能", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 设置布局点击事件
        layoutFloatWindow.setOnClickListener(v -> {
            switchFloatWindow.setChecked(!switchFloatWindow.isChecked());
            
            if (switchFloatWindow.isChecked()) {
                // 请求悬浮窗权限
                requestFloatWindowPermission();
            } else {
                // 关闭悬浮窗功能
                Toast.makeText(MainActivity.this, "已关闭悬浮窗功能", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * 检查是否有悬浮窗权限
     */
    private boolean checkFloatWindowPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(this);
        } else {
            return true; // 在Android 6.0之前，默认允许
        }
    }
    
    /**
     * 请求悬浮窗权限
     */
    private void requestFloatWindowPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                Uri uri = Uri.parse("package:" + getPackageName());
                intent.setData(uri);
                startActivityForResult(intent, REQUEST_FLOAT_WINDOW);
            } else {
                // 已有权限，可以显示悬浮窗
                Toast.makeText(this, "悬浮窗权限已授予", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 初始化屏幕录制开关
     */
    private void setupScreenRecordingSwitch() {
        // 获取屏幕录制布局和开关
        LinearLayout layoutScreenRecording = findViewById(R.id.layout_screen_record);
        switchScreenRecording = findViewById(R.id.switch_screen_record);
        
        // 设置开关初始状态为关闭
        switchScreenRecording.setChecked(false);
        
        // 设置开关点击事件
        switchScreenRecording.setOnClickListener(v -> {
            // 如果用户尝试打开屏幕录制
            if (switchScreenRecording.isChecked()) {
                // 将开关状态重置为关闭，等待权限验证后再开启
                switchScreenRecording.setChecked(false);
                // 请求屏幕录制权限
                requestMediaProjectionPermission();
            }
        });
        
        // 设置布局点击事件
        layoutScreenRecording.setOnClickListener(v -> {
            // 如果当前状态为关闭，表示用户想要开启
            if (!switchScreenRecording.isChecked()) {
                // 请求屏幕录制权限（不改变开关状态）
                requestMediaProjectionPermission();
            } else {
                // 如果当前状态为开启，用户想要关闭，直接关闭
                switchScreenRecording.setChecked(false);
                Toast.makeText(MainActivity.this, "已关闭屏幕录制功能", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    /**
     * 请求屏幕录制权限
     */
    private void requestMediaProjectionPermission() {
        MediaProjectionManager projectionManager = 
                (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
        startActivityForResult(
                projectionManager.createScreenCaptureIntent(),
                REQUEST_MEDIA_PROJECTION);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_FLOAT_WINDOW) {
            // 检查权限结果
            boolean hasPermission = checkFloatWindowPermission();
            switchFloatWindow.setChecked(hasPermission);
            
            if (hasPermission) {
                Toast.makeText(this, "悬浮窗权限已授予", Toast.LENGTH_SHORT).show();
                // 在这里可以启动悬浮窗服务
            } else {
                Toast.makeText(this, "未获得悬浮窗权限", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_MEDIA_PROJECTION) {
            if (resultCode == RESULT_OK) {
                // 权限已授予，设置开关状态为开启
                switchScreenRecording.setChecked(true);
                Toast.makeText(this, "屏幕录制权限已授予", Toast.LENGTH_SHORT).show();
                
                // 在这里可以添加开始录制的逻辑
                // 例如：startScreenRecording(data);
                
            } else {
                // 用户拒绝了权限
                switchScreenRecording.setChecked(false);
                Toast.makeText(this, "未获得屏幕录制权限", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 设置沉浸式状态栏，使应用内容延伸到状态栏
     */
    private void setImmersiveStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | 
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );
            // 使用我们定义的colorPrimary颜色资源
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimary));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // 修正为使用Android原生API的WindowInsetsController
                getWindow().getInsetsController().setSystemBarsAppearance(
                        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS,
                        WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS);
            } else {
                getWindow().getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE | 
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                );
            }
        }
    }
    
    private void loadPluginsFromJson() {
        try {
            // 从assets目录读取插件配置文件
            String jsonString = readAssetFile("plugins.json");
            
            // 解析JSON数组
            pluginsArray = new JSONArray(jsonString);
            
        } catch (JSONException e) {
            Log.e(TAG, "JSON解析错误: " + e.getMessage());
            Toast.makeText(this, "加载插件数据失败", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Log.e(TAG, "读取文件错误: " + e.getMessage());
            Toast.makeText(this, "读取插件配置文件失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private String readAssetFile(String fileName) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        
        try (InputStream is = getAssets().open(fileName);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            
            String line;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
        }
        
        return stringBuilder.toString();
    }
    
    private void setupPluginRecyclerView() {
        rvPlugins = findViewById(R.id.rv_plugins);
        rvPlugins.setLayoutManager(new LinearLayoutManager(this));
        
        pluginAdapter = new PluginAdapter(this, pluginsArray);
        pluginAdapter.setOnItemClickListener((position, pluginObject) -> {
            try {
                // 创建Intent跳转到PluginActivity
                Intent intent = new Intent(MainActivity.this, PluginActivity.class);
                // 传递插件数据
                intent.putExtra("plugin", true);
                intent.putExtra("plugin_type", pluginObject.getString("type"));
                intent.putExtra("plugin_name", pluginObject.getString("name"));
                intent.putExtra("plugin_description", pluginObject.getString("description"));
                intent.putExtra("plugin_logo", pluginObject.getString("avatar"));
                // 传递nickname，如果存在
                if (pluginObject.has("nickname")) {
                    intent.putExtra("plugin_nickname", pluginObject.getString("nickname"));
                }
                intent.putExtra("plugin_views", pluginObject.getJSONArray("views").toString());
                // 启动Activity
                startActivity(intent);
            } catch (JSONException e) {
                Log.e(TAG, "JSON解析错误: " + e.getMessage());
                Toast.makeText(MainActivity.this, "插件数据错误", Toast.LENGTH_SHORT).show();
            }
        });
        
        rvPlugins.setAdapter(pluginAdapter);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_market) {
            Intent intent = new Intent(this, MarketActivity.class);
            startActivity(intent);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    public void onBackPressed() {
        // 如果抽屉菜单处于打开状态，返回键会先关闭抽屉菜单
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}